<template>
    <div class="category-management">
        <!-- Search Form -->
        <el-form>
            <el-row :gutter="20" class="mb-4">
                <el-col :span="6">
                    <el-form-item label="一级目录">
                        <el-select v-model="filters.firstLevel" filterable remote reserve-keyword clearable
                            placeholder="选择一级目录" :loading="loading" :remote-method="remoteMethodF" @change="changeF"
                            style="width: 240px">
                            <el-option v-for="item in optionsF" :key="item.id" :label="item.name" :value="item.name" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="二级目录">
                        <el-select v-model="filters.secondLevel" filterable remote reserve-keyword clearable
                            :disabled="filters.firstLevel == '' || filters.categoryName != ''" placeholder="选择二级目录"
                            :loading="loading" style="width: 240px">
                            <el-option v-for="item in optionsS" :key="item.id" :label="item.name" :value="item.name" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="品类名称">
                        <el-select v-model="filters.categoryName" filterable remote reserve-keyword clearable
                            placeholder="选择品类" :loading="loading" :remote-method="remoteMethodC" @change="changeC"
                            style="width: 240px">
                            <el-option v-for="item in optionsC" :key="item.id" :label="item.categoryName"
                                :value="item.categoryName" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6" class="text-right">
                    <el-button type="primary" @click="handleQuery">查询</el-button>
                    <el-button type="primary" @click="handleAdd">新建</el-button>
                </el-col>
            </el-row>
        </el-form>

        <!-- Table -->
        <el-table :data="tableData" style="width: 100%">
            <el-table-column prop="id" label="序号" width="70" />
            <el-table-column prop="firstLevel" label="一级目录" />
            <el-table-column prop="secondLevel" label="二级目录" />
            <el-table-column prop="categoryName" label="品类名称" />
            <el-table-column prop="unit" label="单位" />
            <el-table-column prop="specification" label="规格" />
            <el-table-column label="操作" width="150" fixed="right">
                <template #default="scope">
                    <el-button link type="primary" size="small" @click="handleEdit(scope.row)"
                        :disabled="user.status == 2">
                        修改
                    </el-button>
                    <el-button link type="danger" size="small" @click="handleDelete(scope.row)"
                        :disabled="user.status == 2">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- Pagination -->
        <div class="flex justify-between items-center mt-4">
            <span class="text-sm text-gray-500">
                共 {{ total }} 条记录 第 {{ currentPage }} / {{ totalPages }} 页
            </span>
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 15]"
                :small="small" :disabled="disabled" :background="background"
                layout="total, prev, pager, next, sizes, jumper" :total="total" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </div>
        <el-dialog v-model="dialogVisible" :title="operation == 1 ? '新增品类' : '修改品类'" width="50%">
            <el-form :model="form" label-width="120px">
                <el-form-item label="一级目录">
                    <el-select v-model="form.firstLevel" filterable remote reserve-keyword
                        placeholder="Please enter a keyword" :loading="loading" :remote-method="remoteMethodF"
                        @change="changeFD" style="width: 240px">
                        <el-option v-for="item in optionsF" :key="item.id" :label="item.name" :value="item.name" />
                    </el-select>
                </el-form-item>
                <el-form-item label="二级目录">
                    <el-select v-model="form.secondLevel" filterable remote reserve-keyword
                        :disabled="form.firstLevel == ''" placeholder="Please enter a keyword" :loading="loading"
                        style="width: 240px">
                        <el-option v-for="item in optionsSD" :key="item.id" :label="item.name" :value="item.name" />
                    </el-select>
                </el-form-item>
                <el-form-item label="品类名称">
                    <el-input v-model="form.categoryName" />
                </el-form-item>
                <el-form-item label="单位">
                    <el-input v-model="form.unit" />
                </el-form-item>
                <el-form-item label="规格">
                    <el-input v-model="form.specification" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { getCategoryPage, saveCategory, getLevelFirst, searchLevel, delCategory, findAllCategory } from '@/utils/category';
import { ElMessage } from 'element-plus';

// Data
const filters = ref({
    firstLevel: '',
    secondLevel: '',
    categoryName: ''
})
const user = ref(localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {})
const dialogVisible = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(400)
const operation = ref(1)
const loading = ref(false)
const optionsF = ref([])
const optionsS = ref([])
const optionsSD = ref([])
const optionsC = ref([])

const form = ref({
    firstLevel: '',
    unit: '',
    specification: '',
    secondLevel: '',
    categoryName: ''
})

const formRes = {
    firstLevel: '',
    unit: '',
    specification: '',
    secondLevel: '',
    categoryName: ''
}

const tableData = ref([])

onMounted(() => {
    search()
})

// Computed
const totalPages = computed(() => Math.ceil(total.value / pageSize.value))

// Methods
const search = () => {
    getCategoryPage(filters.value, currentPage.value, pageSize.value).then(res => {
        if (res.code == 200) {
            tableData.value = res.data.records
            total.value = res.data.total
        } else {
            ElMessage.error(res.message)
        }
    })
}

const handleQuery = () => {
    search()
}

const submitForm = () => {
    saveCategory(form.value).then(res => {
        if (res.code == 200) {
            dialogVisible.value = false
            search()
        } else {
            ElMessage.error(res.message)
        }
    })
}

const handleAdd = () => {
    operation.value = 1
    form.value = JSON.parse(JSON.stringify(formRes))
    dialogVisible.value = true
}

const handleEdit = (row) => {
    operation.value = 2
    form.value = JSON.parse(JSON.stringify(row))
    dialogVisible.value = true
}

const handleDelete = (row) => {
    ElMessageBox.confirm(
        '确认删除该记录吗？',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            delCategory(row.id).then(res => {
                if (res.code == 200) {
                    ElMessage.success(`删除记录: ${row.id}`)
                    search()
                } else {
                    ElMessage.error(res.message)
                }
            })
        })
        .catch(() => {
            ElMessage.info('已取消删除')
        })
}

const handleSizeChange = (val) => {
    pageSize.value = val
    search()
}

const handleCurrentChange = (val) => {
    currentPage.value = val
    search()
}

const remoteMethodF = (query) => {
    loading.value = true
    setTimeout(() => {
        loading.value = false
        getLevelFirst().then(res => {
            if (res.code == 200) {
                optionsF.value = res.data.filter((item) => {
                    return item.name.toLowerCase().includes(query.toLowerCase())
                })
            } else {
                ElMessage.error(res.message)
            }
        })
    }, 200)
}

const changeF = () => {
    filters.value.secondLevel = ''
    searchLevel({ name: filters.value.firstLevel }).then(res => {
        if (res.code == 200) {
            optionsS.value = res.data[0].children
        } else {
            ElMessage.error(res.message)
        }
    })
}

const changeFD = () => {
    form.value.secondLevel = ''
    searchLevel({ name: form.value.firstLevel }).then(res => {
        if (res.code == 200) {
            optionsSD.value = res.data[0].children
        } else {
            ElMessage.error(res.message)
        }
    })
}

const changeC = (name) => {
    optionsC.value.forEach(element => {
        if (element.categoryName == name) {
            filters.value.firstLevel = element.firstLevel
            filters.value.secondLevel = element.secondLevel
        }
    });
    searchLevel({ name: filters.value.firstLevel }).then(res => {
        if (res.code == 200) {
            optionsS.value = res.data[0].children
        } else {
            ElMessage.error(res.message)
        }
    })
}

const remoteMethodC = (query) => {
    loading.value = true
    setTimeout(() => {
        findAllCategory({ firstLevel: filters.value.firstLevel, secondLevel: filters.value.secondLevel, categoryName: query }).then(res => {
            if (res.code == 200) {
                loading.value = false
                optionsC.value = res.data
            } else {
                ElMessage.error(res.message)
            }
        })
    }, 200)
}
</script>

<style scoped>
.el-pagination {
    float: right;
}
</style>